package com.lovo.system.controller;


import com.lovo.system.config.RedisCacheUtil;
import com.lovo.system.mapper.GoodsMapper;
import com.lovo.system.model.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lovo
 * @since 2021-02-01
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    RedisCacheUtil redisCacheUtil;

    @GetMapping("/getGoodsList")
    public List<Goods> getList(){
        List<Goods> goodsList = goodsMapper.selectList(null);
        System.out.println("goodsList = " + goodsList);

        //根据时间来判断能否购买重新设定status
        Date date0 =new Date();//现在的时间;
        //goodsList2用来返回
        List<Goods> goodsList2 =new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Goods goods:goodsList) {
            try {
                Date dateStart =format.parse(goods.getGoodsStartTime());
                Date dateEnd =format.parse(goods.getGoodsEndTime());
                int num1 = dateStart.compareTo(date0);
                int num2 = dateEnd.compareTo(date0);
                System.out.println("num1 = " + num1);
                System.out.println("num2 = " + num2);
                if(num1<=0&&num2<=1&&num2>=0){
                    goods.setGoodsStatus("ok");
                    //ok代表可以购买
                }else if(num1==1){
                    goods.setGoodsStatus("before");
                    //before代表还没到时间
                }else if(num2==-1){
                    goods.setGoodsStatus("after");
                    //
                }

                goodsList2.add(goods);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }



        //查询出来放到redis里面
        boolean b = redisCacheUtil.hset("goodsList", "goodsListItem", goodsList2);
        if(b){
            System.out.println("缓存添加成功");
        }

        return goodsList2;
    }
    //从缓存中得到数据
    @GetMapping("/getGoodsListByRedis")
    public List<Goods> getListByRedis(){
        List<Goods> goods =(List<Goods>)redisCacheUtil.hget("goodsList","goodsListItem");
        System.out.println("goods = " + goods);
        return goods;

    }


}
